route.ts 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import { NextRequest, NextResponse } from "next/server";
  2. import { STORAGE_KEY, internalAllowedWebDavEndpoints } from "../../../constant";
  3. import { getServerSideConfig } from "@/app/config/server";
  4. const config = getServerSideConfig();
  5. const mergedAllowedWebDavEndpoints = [
  6. ...internalAllowedWebDavEndpoints,
  7. ...config.allowedWebDevEndpoints,
  8. ].filter((domain) => Boolean(domain.trim()));
  9. const normalizeUrl = (url: string) => {
  10. try {
  11. return new URL(url);
  12. } catch (err) {
  13. return null;
  14. }
  15. };
  16. async function handle(
  17. req: NextRequest,
  18. { params }: { params: { path: string[] } },
  19. ) {
  20. if (req.method === "OPTIONS") {
  21. return NextResponse.json({ body: "OK" }, { status: 200 });
  22. }
  23. const folder = STORAGE_KEY;
  24. const fileName = `${folder}/backup.json`;
  25. const requestUrl = new URL(req.url);
  26. let endpoint = requestUrl.searchParams.get("endpoint");
  27. // Validate the endpoint to prevent potential SSRF attacks
  28. if (
  29. !endpoint ||
  30. !mergedAllowedWebDavEndpoints.some((allowedEndpoint) => {
  31. const normalizedAllowedEndpoint = normalizeUrl(allowedEndpoint);
  32. const normalizedEndpoint = normalizeUrl(endpoint as string);
  33. return normalizedEndpoint &&
  34. normalizedEndpoint.hostname === normalizedAllowedEndpoint?.hostname &&
  35. normalizedEndpoint.pathname.startsWith(normalizedAllowedEndpoint.pathname);
  36. })
  37. ) {
  38. return NextResponse.json(
  39. {
  40. error: true,
  41. msg: "Invalid endpoint",
  42. },
  43. {
  44. status: 400,
  45. },
  46. );
  47. }
  48. if (!endpoint?.endsWith("/")) {
  49. endpoint += "/";
  50. }
  51. const endpointPath = params.path.join("/");
  52. const targetPath = `${endpoint}${endpointPath}`;
  53. // only allow MKCOL, GET, PUT
  54. if (req.method !== "MKCOL" && req.method !== "GET" && req.method !== "PUT") {
  55. return NextResponse.json(
  56. {
  57. error: true,
  58. msg: "you are not allowed to request " + targetPath,
  59. },
  60. {
  61. status: 403,
  62. },
  63. );
  64. }
  65. // for MKCOL request, only allow request ${folder}
  66. if (req.method === "MKCOL" && !targetPath.endsWith(folder)) {
  67. return NextResponse.json(
  68. {
  69. error: true,
  70. msg: "you are not allowed to request " + targetPath,
  71. },
  72. {
  73. status: 403,
  74. },
  75. );
  76. }
  77. // for GET request, only allow request ending with fileName
  78. if (req.method === "GET" && !targetPath.endsWith(fileName)) {
  79. return NextResponse.json(
  80. {
  81. error: true,
  82. msg: "you are not allowed to request " + targetPath,
  83. },
  84. {
  85. status: 403,
  86. },
  87. );
  88. }
  89. // for PUT request, only allow request ending with fileName
  90. if (req.method === "PUT" && !targetPath.endsWith(fileName)) {
  91. return NextResponse.json(
  92. {
  93. error: true,
  94. msg: "you are not allowed to request " + targetPath,
  95. },
  96. {
  97. status: 403,
  98. },
  99. );
  100. }
  101. const targetUrl = targetPath;
  102. const method = req.method;
  103. const shouldNotHaveBody = ["get", "head"].includes(
  104. method?.toLowerCase() ?? "",
  105. );
  106. const fetchOptions: RequestInit = {
  107. headers: {
  108. authorization: req.headers.get("authorization") ?? "",
  109. },
  110. body: shouldNotHaveBody ? null : req.body,
  111. redirect: "manual",
  112. method,
  113. // @ts-ignore
  114. duplex: "half",
  115. };
  116. let fetchResult;
  117. try {
  118. fetchResult = await fetch(targetUrl, fetchOptions);
  119. } finally {
  120. console.log(
  121. "[Any Proxy]",
  122. targetUrl,
  123. {
  124. method: req.method,
  125. },
  126. {
  127. status: fetchResult?.status,
  128. statusText: fetchResult?.statusText,
  129. },
  130. );
  131. }
  132. return fetchResult;
  133. }
  134. export const PUT = handle;
  135. export const GET = handle;
  136. export const OPTIONS = handle;
  137. export const runtime = "edge";